<template>
	<view class="cart-page">
		<!-- 登录提示 -->
		<view class="login-tip" v-if="!isLogin">
			<text>登录后可同步购物车中商品</text>
			<button class="login-btn" @click="navigateToLogin">登录</button>
		</view>
		<!-- 购物车列表 -->
		<view class="cart-list" v-if="cartData.length > 0">
			<view class="cart-item" v-for="(item, index) in cartData" :key="item.id">
				<label class="checkbox">
					<checkbox :value="item.id" :checked="item.checked" @click="toggleCheck(index)" />
				</label>

				<image class="product-img" :src="'http://localhost:3000/' + item.productImg" mode="aspectFill"></image>

				<view class="product-info">
					<text class="product-name">{{item.productName}}</text>
					<text class="product-price">¥{{item.price}}</text>

					<view class="quantity-control">
						<text class="quantity-btn" @click="decreaseQuantity(index, item.productID)">-</text>
						<input type="number" class="quantity-input" v-model="item.num"
							@blur="validateQuantity(index, item.productID)" />
						<text class="quantity-btn" @click="increaseQuantity(index, item.productID)">+</text>
					</view>
				</view>

				<view class="delete-btn" @click="showDeleteConfirm(index, item.id, item.productID)">
					<text class="iconfont">×</text>
				</view>
			</view>
		</view>

		<!-- 空购物车 -->
		<view class="empty-cart" v-else>
			<image src="/static/empty-cart.png" mode="aspectFit"></image>
			<text class="empty-text">购物车空空如也</text>
			<button class="shopping-btn" @click="navigateToHome">去逛逛</button>
		</view>

		<!-- 底部结算栏 -->
		<view class="cart-footer">
			<label class="footer-checkbox">
				<checkbox :checked="isAllChecked" @click="toggleAllCheck" />全选
			</label>

			<view class="footer-right">
				<view class="total-price">
					合计: <text class="price">¥{{totalPrice.toFixed(2)}}</text>
				</view>
				<button class="checkout-btn" :class="{disabled: selectedCount === 0}" :disabled="selectedCount === 0"
					@click="handleCheckout">
					结算({{selectedCount}})
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseUrl: 'http://localhost:8081', // 替换为您的后端API地址
				isLogin: false,
				userInfo: null,
				cartData: []
			}
		},
		computed: {
			isAllChecked() {
				if (this.cartData.length === 0) return false
				return this.cartData.every(item => item.checked)
			},
			selectedCount() {
				return this.cartData.filter(item => item.checked).length
			},
			totalPrice() {
				return this.cartData
					.filter(item => item.checked)
					.reduce((total, item) => total + (item.price * item.num), 0)
			}
		},
		onShow() {
			this.checkLoginStatus()
			this.loadCartData()
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				try {
					const userInfo = uni.getStorageSync('userInfo')
					this.userInfo = userInfo
					this.isLogin = !!userInfo && !!userInfo.user_id
				} catch (e) {
					console.error('获取登录状态失败:', e)
					this.isLogin = false
				}
			},

			// 加载购物车数据
			async loadCartData() {
				if (!this.isLogin) {
					this.loadLocalCart()
					return
				}

				// uni.showLoading({
				// 	title: '加载中...'
				// })

				const res = await uni.request({
					url: `${this.baseUrl}/api/user/shoppingCart/getShoppingCart`,
					method: 'POST',
					data: {
						user_id: this.userInfo.user_id
					}
				})

				this.cartData = res.data.shoppingCartData.map(item => ({
					...item,
					checked: false
				}))

			},

			// 加载本地购物车
			loadLocalCart() {
				try {
					const localCart = uni.getStorageSync('localCart') || []
					this.cartData = localCart
				} catch (e) {
					console.error('读取本地购物车失败:', e)
				}
			},

			// 保存本地购物车
			saveLocalCart() {
				if (this.isLogin) return

				try {
					uni.setStorageSync('localCart', this.cartData)
				} catch (e) {
					console.error('保存本地购物车失败:', e)
				}
			},

			// 切换选中状态
			toggleCheck(index) {
				this.cartData[index].checked = !this.cartData[index].checked
				this.saveLocalCart()
			},

			// 全选/反选
			toggleAllCheck() {
				const shouldCheck = !this.isAllChecked
				this.cartData.forEach(item => {
					item.checked = shouldCheck
				})
				this.saveLocalCart()
			},

			// 减少数量
			decreaseQuantity(index, productID) {
				if (this.cartData[index].num > 1) {
					this.cartData[index].num--
					this.updateQuantity(index, productID)
				}
			},

			// 增加数量
			increaseQuantity(index, productID) {
				if (this.cartData[index].num < this.cartData[index].maxNum) {
					this.cartData[index].num++
					this.updateQuantity(index, productID)
				} else {
					uni.showToast({
						title: `已达到限购数量${this.cartData[index].maxNum}`,
						icon: 'none'
					})
				}
			},

			// 验证数量输入
			validateQuantity(index, productID) {
				let num = this.cartData[index].num
				if (isNaN(num) || num < 1) {
					num = 1
				} else if (num > this.cartData[index].maxNum) {
					num = this.cartData[index].maxNum
					uni.showToast({
						title: `已达到限购数量${num}`,
						icon: 'none'
					})
				}
				this.cartData[index].num = num
				this.updateQuantity(index, productID)
			},

			// 更新数量
			async updateQuantity(index, productID) {
				const item = this.cartData[index]

				if (this.isLogin) {
					const res = await uni.request({
						url: `${this.baseUrl}/api/user/shoppingCart/UpdateShoppingCart`,
						method: 'POST',
						data: {
							user_id: this.userInfo.user_id,
							product_id: productID,
							num: item.num
						}
					})
					this.loadCartData()


				} else {
					this.saveLocalCart()
				}
			},

			// 显示删除确认
			showDeleteConfirm(index, id, productID) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个商品吗？',
					success: (res) => {
						if (res.confirm) {
							this.deleteItem(index, id, productID)
						}
					}
				})
			},

			// 删除商品
			async deleteItem(index, id, productID) {
				if (this.isLogin) {
					const res = await uni.request({
						url: `${this.baseUrl}/api/user/shoppingCart/DeleteShoppingCart`,
						method: 'POST',
						data: {
							user_id: this.userInfo.user_id,
							product_id: productID
						}
					})

					this.cartData.splice(index, 1)
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
					this.loadCartData()

				} else {
					this.cartData.splice(index, 1)
					this.saveLocalCart()
					uni.showToast({
						title: '删除成功',
						icon: 'success'
					})
				}
			},

			// 结算
			handleCheckout() {
				// 1. 检查是否有选中商品
				if (this.selectedCount === 0) {
					uni.showToast({
						title: '请选择要结算的商品',
						icon: 'none'
					})
					return
				}

				// 2. 显示加载状态
				uni.showLoading({
					title: '准备结算...',
					mask: true
				})

				// 3. 检查登录状态
				if (!this.isLogin) {
					uni.hideLoading()
					uni.showModal({
						title: '未登录',
						content: '请先登录再结算',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								this.navigateToLogin()
							}
						}
					})
					return
				}

				// 4. 准备数据并跳转
				try {
					const selectedItems = this.cartData.filter(item => item.checked)

					// 存储选中商品数据
					uni.setStorageSync('checkoutItems', selectedItems)

					// 执行跳转
					uni.navigateTo({
						url: '/pages/confirmOrder/confirmOrder',
						success: () => {
							uni.hideLoading()
						},
						fail: (err) => {
							uni.hideLoading()
							console.error('跳转失败:', err)
							uni.showToast({
								title: '跳转失败',
								icon: 'none'
							})
						}
					})
				} catch (error) {
					uni.hideLoading()
					console.error('处理结算出错:', error)
					uni.showToast({
						title: '处理结算出错',
						icon: 'none'
					})
				}
			},

			// 跳转登录
			navigateToLogin() {
				uni.navigateTo({
					url: '/pages/login/login'
				})
			},

			// 跳转首页
			navigateToHome() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style>
	/* 基础样式 */
	.cart-page {
		padding-bottom: 100px;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 登录提示样式 */
	.login-tip {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 15px;
		background-color: #fff8e6;
		font-size: 14px;
		color: #f90;
	}

	.login-btn {
		margin: 0;
		padding: 0 15px;
		height: 30px;
		line-height: 30px;
		font-size: 12px;
		color: #f90;
		border: 1px solid #f90;
		border-radius: 15px;
		background-color: transparent;
	}

	/* 购物车列表样式 */
	.cart-list {
		margin: 10px;
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
	}

	.cart-item {
		display: flex;
		align-items: center;
		padding: 15px;
		border-bottom: 1px solid #eee;
	}

	.checkbox {
		margin-right: 10px;
	}

	.product-img {
		width: 80px;
		height: 80px;
		border-radius: 4px;
		margin-right: 10px;
	}

	.product-info {
		flex: 1;
	}

	.product-name {
		font-size: 15px;
		color: #333;
		margin-bottom: 10px;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.product-price {
		font-size: 16px;
		color: #f40;
		font-weight: bold;
		margin-bottom: 10px;
		display: block;
	}

	.quantity-control {
		display: flex;
		align-items: center;
	}

	.quantity-btn {
		width: 30px;
		height: 30px;
		line-height: 30px;
		text-align: center;
		border: 1px solid #ddd;
		font-size: 16px;
		cursor: pointer;
	}

	.quantity-input {
		width: 40px;
		height: 30px;
		text-align: center;
		border-top: 1px solid #ddd;
		border-bottom: 1px solid #ddd;
		border-left: none;
		border-right: none;
	}

	.delete-btn {
		width: 40px;
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 20px;
		color: #999;
		cursor: pointer;
	}

	/* 空购物车样式 */
	.empty-cart {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 100px;
	}

	.empty-cart image {
		width: 200px;
		height: 200px;
		margin-bottom: 20px;
	}

	.empty-text {
		font-size: 16px;
		color: #999;
		margin-bottom: 30px;
	}

	.shopping-btn {
		width: 200px;
		height: 40px;
		line-height: 40px;
		background-color: #f40;
		color: #fff;
		border-radius: 20px;
		font-size: 15px;
		border: none;
	}

	/* 底部结算栏样式 */
	.cart-footer {
		position: absolute;
		bottom: 1%;
		left: 0;
		right: 0;
		height: 50px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 15px;
		background-color: #fff;
		border-top: 1px solid #eee;
		z-index: 10;
	}

	.footer-checkbox {
		display: flex;
		align-items: center;
		font-size: 14px;
	}

	.footer-right {
		display: flex;
		align-items: center;
	}

	.total-price {
		margin-right: 15px;
		font-size: 14px;
	}

	.price {
		font-size: 16px;
		color: #f40;
		font-weight: bold;
	}

	.checkout-btn {
		width: 120px;
		height: 40px;
		background-color: #f40;
		color: #fff;
		border-radius: 20px;
		font-size: 14px;
		border: none;
		cursor: pointer;
	}

	.checkout-btn.disabled {
		background-color: #ccc;
		cursor: not-allowed;
	}
</style>